(function ($) {
    $.fn.yqTextAttr = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqTextAttr.methods[opts](this, param);
        }

        var $this = this;
        var opt = $.extend({}, $.fn.yqTextAttr.defaults, opts);

        if ($this.data("yqtype") == "yqTableEdit") {
            var $uniqueID = $this.attr("ID");
            destroy($this);
            $this = $("#" + $uniqueID);
        }
        else {
            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        if (opt.width === undefined && $this.width() > 0) {
            opt.width = $this.width();
        }
        else if (typeof opt.width != "undefined") {
            $this.width(opt.width);
        }

        //转换编辑尺寸
        if (typeof opt.editModeW == "string") {
            var r_str = opt.editModeW.substring(opt.editModeW.length - 1, opt.editModeW.length);
            if (r_str == "%") {
                var wSacle = parseInt(opt.editModeW.substring(0, opt.editModeW.length - 1));
                opt.editModeW = parseInt(wSacle * $(window).width() / 100);
            } else {
                opt.editModeW = parseInt(opt.editModeW);
            }
        }
        if (typeof opt.editModeH == "string") {
            var r_str = opt.editModeH.substring(opt.editModeH.length - 1, opt.editModeH.length);
            if (r_str == "%") {
                var wSacle = parseInt(opt.editModeH.substring(0, opt.editModeH.length - 1));
                opt.editModeH = parseInt(wSacle * $(window).height() / 100);
            } else {
                opt.editModeH = parseInt(opt.editModeH);
            }
        }

        opt.onload = true;

        if(opt.editType==1 ||opt.editType==2){
            opt.editType=1;
        }

        //变量信息
        $this.data("textattr_opt", opt);
        $this.data("yqtype", "yqTextAttr");

        init_text_before($this);
    };

    $.fn.yqTextAttr.defaults = {
        ajaxUrl: "/_db.html",
        editType: 1,  //1:属性编辑模式  2:form编辑模式
        titles: [],  //数据列配置对象
        model: null,
        row: {},
        loadDefault: false,   //加载默认值
        isEdit: true,   //可编辑
        blankTag: "*",     //值不能为空，标题附加标记
        removeUnUse: false, //移除未使用的列

        editModeW: 800, //模态编辑器宽度 格式为 800（数字）
        editModeH: 600, //模态编辑器高度 格式为 600（数字）
        beforeBindingTitle: function (titles, callback) {
            callback(titles);
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
        
        beforeEditShow:function(run_opt){
            return run_opt;
        }, //弹出框显示前
        
        beforeChange: function (value, callback) {    //弹出框中的事件
            callback(true, value);
        },
        afterChange: function (value) { //修改后

        }
    };

    $.fn.yqTextAttr.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        },
        clear: function (jq, data) {
            setRow($(jq[0]), []);
        },
        setRow: function (jq, rows) {
            setRow($(jq[0]), rows);
        },
        getRow: function (jq) {
            return getRow($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("textattr_opt");
    }

    function destroy($object) {
        $object.textbox("destroy");
    }

    function resize($object, width) {
        $object.textbox("resize", width);
    }

    function init_text_before($object) {
        var opt = options($object);
        opt.beforeBindingTitle.call($object, opt.titles,
            function (titles) {
                opt.titles = titles;
                init_text($object);
            });
    }

    function init_text($object) {
        var opt = options($object);

        var text_opt = {
            editable: false,
            iconAlign: 'right',
            icons: [{
                iconCls: 'yqwin-combo-btn-icon fa fa-pencil',
                handler: function (e) {
                    var pp = $object.textbox("textbox");
                    prevent_e = $.getPreventDefault(pp[0]);
                    prevent_e.id = $object.attr("id");
                    prevent_e.options = opt;

                    var mdiinfo = $.yqGetWindParams();

                    if (opt.editType == 1) {
                        var run_opt = {
                            mdiinfo: mdiinfo,
                            prevent_e: prevent_e,

                            ajaxUrl: opt.ajaxUrl,
                            titles: opt.titles,
                            row: opt.row,
                            isEdit: opt.isEdit,

                            loadDefault: opt.loadDefault,   //加载默认值
                            blankTag: opt.blankTag,     //值不能为空，标题附加标记
                            removeUnUse:opt.removeUnUse, //移除未使用的列

                            width: opt.editModeW,
                            height: opt.editModeH,

                            callback: function (row) {
                                //嵌入到datagrid中，兼容处理（需要重新创建对象）
                                if (typeof opt.p_target != "undefined") {
                                    var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                                    if (!(ed === null)) {
                                        $(ed.target).yqTextAttr('setRow', row);
                                        opt.afterChange.call($(ed.target), row);
                                    }
                                }
                                else {
                                    opt.row = row;
                                    $object.textbox("setText", JSON.stringify(row));
                                    opt.afterChange.call($object, row);
                                }
                            }
                        };
 
                        run_opt =opt.beforeEditShow.call($object, run_opt);

                        if (window.top == window.self) {
                            $.yqAttrPopEdit(run_opt);
                        }
                        else {
                            window.top.$.yqAttrPopEdit(run_opt);
                        }
                    } else if (opt.editType == 2) {
                        var run_opt = {
                            mdiinfo: mdiinfo,
                            prevent_e: prevent_e,

                            ajaxUrl: opt.ajaxUrl,
                            titles: opt.titles,
                            model: null,
                            row: opt.row,
                            isEdit: opt.isEdit,

                            loadDefault: opt.loadDefault,   //加载默认值
                            blankTag: opt.blankTag,     //值不能为空，标题附加标记
                            removeUnUse:opt.removeUnUse, //移除未使用的列

                            width: opt.editModeW,
                            height: opt.editModeH,

                            callback: function (row) {
                                opt.row = row;
                                //嵌入到datagrid中，兼容处理（需要重新创建对象）
                                if (typeof opt.p_target != "undefined") {
                                    var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                                    if (!(ed === null)) {
                                        $(ed.target).yqTextAttr('setRow', row);
                                    }
                                }
                                else {
                                    $object.textbox("setText", JSON.stringify(row));
                                }
                            }
                        };

                        run_opt =opt.beforeEditShow.call($object, run_opt);

                        if (window.top == window.self) {
                            $.yqFormPopEdit(run_opt);
                        }
                        else {
                            window.top.$.yqFormPopEdit(run_opt);
                        }
                    }
                }
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-times',
                handler: function (e) {
                    setRow($object, {});
                    opt.afterChange.call($object, {});
                }
            }]
        };

        $object.textbox(text_opt);

        setRow($object, opt.row);
        isEdit($object, opt.isEdit);

        opt.afterBindingTitle.call($object);
    }


    function isEdit($object, tf) {
        var opt = options($object);
        var icon0 = $object.textbox("getIcon", 0);
        var icon1 = $object.textbox("getIcon", 1);
        opt.isEdit = tf;
        if (opt.isEdit) {
            icon0.removeClass('icon-more');
            icon0.addClass('icon-edit');
            icon1.show();
            //icon1.removeClass('textbox-icon-disabled');
        } else {
            icon0.removeClass('icon-edit');
            icon0.addClass('icon-more');
            //icon1.addClass('textbox-icon-disabled');
            icon1.hide();
        }
    }

    function setRow($object, row) {
        var opt = options($object);
        if (row === undefined || row === null || row == "") {
            row = {};
        }
        if (typeof row == "string") {
            opt.row = JSON.parse(row);
        } else {
            opt.row = $.extend({}, row);
        }

        setText($object);
    }

    function getRow($object) {
        var opt = options($object);

        if(opt.row === undefined || opt.row === null){
            opt.row = null;
        }else if (Object.getOwnPropertyNames(opt.row) == 0) {
            opt.row = null;
        }

        return opt.row;
    }

    function setText($object) {
        var opt = options($object);

        if (Object.getOwnPropertyNames(opt.row) == 0) {
            $object.textbox("setText", "");
        }
        else {
            $object.textbox("setText", JSON.stringify(opt.row));
        }
    }
})(jQuery);
